package com.ken.base_http_library

import com.google.gson.GsonBuilder
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class ServiceCreator private constructor() {
    var mUrl: String = NEWS_BASE_URL

    companion object {
        val mInstance by lazy(mode = LazyThreadSafetyMode.NONE) {
            ServiceCreator()
        }

        val JUHE_GNYJ_BASE_URL = "http://apis.juhe.cn/"
        val BASE_URL = "https://weizhang.shumaidata.com/"
        val NEWS_BASE_URL = "http://v.juhe.cn/"
    }

    fun get(url: String): ServiceCreator {
        this.mUrl = url
        return mInstance
    }

    private val okHttpClient = OkHttpClient.Builder()
        .connectTimeout(60, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .build()
    private val retrofit = Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(mUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build()


    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)

    inline fun <reified T> create(): T = create(T::class.java)


}